/**
 * 
 */
package vn.tecviets.thuandt.model.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;

/*
 * HTMLFile.java
 * 1.0
 * Mar 22, 2013 9:37:24 AM
 * 
 * Copyright notice
 *
 * Modification Logs:
 *
 * DATE					AUTHOR				DESCRIPTION
 * -----------------------------------------------------------
 * Mar 22, 2013			ThuanDT				Creation
 */

public class HTMLFile {
	public void createFile(String content, String pathname) throws IOException {

			try {
				File file = new File(pathname);
				if (!file.exists()) {
					file.createNewFile();
				}
				FileWriter fw = new FileWriter(file.getAbsoluteFile());
				BufferedWriter bw = new BufferedWriter(fw);
				bw.write(content);
				bw.close();
			} catch (IOException e) {
				throw e;
			}
	}

	/**
	 * @param realPath
	 * @return
	 * @throws IOException 
	 */
	public String readFile(String pathname) throws IOException {

		File file = null;
		FileReader fr = null;
		BufferedReader br = null;
		StringBuilder content = null;

		try {
			file = new File(pathname);
			fr = new FileReader(file);
			br = new BufferedReader(fr);

			content = new StringBuilder();
			String line = null;

			while ((line = br.readLine()) != null) {
				content.append(line);
			}
		} catch (FileNotFoundException e) {
			throw e;
		} catch (IOException e) {
			throw e;
		} finally {
			if (br != null) {
				br.close();
			}

			if (fr != null) {
				fr.close();
			}
		}

		return content.toString();
	}
	
	public void updateFile(String content, String pathname) throws IOException {

		try {
			File file = new File(pathname);
			FileWriter fw = new FileWriter(file);
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(content);
			bw.close();
		} catch (IOException e) {
			throw e;
		}
}

	public void deleteFile(String pathname) {
		try {
			File file = new File(pathname);
			file.delete();
		} catch (NullPointerException e) {
			throw e;
		}
	}

	/**
	 * Check whether file is existed or not
	 * @param pathname
	 * @return true if file is existed. False if it is not exist.
	 */
	public boolean isFileExisted(String pathname) {
		File file = new File(pathname);
		return file.exists();
	}
}
